package cn.sylinx.horm.resource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import cn.sylinx.horm.config.OrmConfigHolder;
import cn.sylinx.horm.resource.io.Resources;
import cn.sylinx.horm.util.GLog;

public enum ReadableClasspathSqlResourceManager {

    ;

    private final static Map<String, String> cache = new HashMap<String, String>();

    public static void clear() {
        cache.clear();
    }

    private static String get(String sqlpath) {
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        String statement = null;
        try {
            is = Resources.getResourceAsStream(sqlpath);
            baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            statement = baos.toString();
        } catch (Exception e) {
            GLog.error("sql resource \"" + sqlpath + "\" not found " + e.getMessage(), e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignored) {
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException ignored) {
                }
            }
        }
        return statement;
    }

    public static void load(String sqlpath) {
        String statement = get(sqlpath);
        if (statement != null) {
            cache.put(sqlpath, statement);
        }
    }

    private static String loadAndGet(String sqlpath) {
        load(sqlpath);
        return cache.get(sqlpath);
    }

    public static String getStatement(String sqlpath) {
        if (OrmConfigHolder.isDebug()) {
            // 如果是调试模式，直接从文件中取
            return get(sqlpath);
        }
        if (cache.containsKey(sqlpath)) {
            GLog.debug("sql bingo: {}", sqlpath);
            return cache.get(sqlpath);
        }

        return loadAndGet(sqlpath);
    }
}